package jsu.lipengcheng.trafficnet.service.Impl;

import jsu.lipengcheng.trafficnet.Util.JwtUtil;
import jsu.lipengcheng.trafficnet.common.BeanThread;
import jsu.lipengcheng.trafficnet.common.UserUpdataPassword;
import jsu.lipengcheng.trafficnet.common.Userlogin;
import jsu.lipengcheng.trafficnet.handler.BenEX;
import jsu.lipengcheng.trafficnet.handler.UserEX;
import jsu.lipengcheng.trafficnet.mapper.UserMapper;
import jsu.lipengcheng.trafficnet.pojo.Users;
import jsu.lipengcheng.trafficnet.service.UserService;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    /**
     * 登录
     * @param users
     * @return
     */
    public Userlogin login(Users users) {
        Users user1 = userMapper.login(users);
        if(user1==null){
            throw new UserEX("用户名或密码错误");
        }
       else if(!user1.getPassword().equals(users.getPassword())){
            throw new UserEX("用户名或密码错误");
        }
       else {
        Map<String,Object> map = new HashMap<String,Object>();
       map.put("userid",user1.getId());
            String token = JwtUtil.createJWT("lipengchengllllll", 360000000L, map);
            Userlogin userlogin=Userlogin.builder()
                   .token(token)
                   .userid(user1.getId())
                   .build();
       return userlogin;}
    }

    @Override
    public void register(Users users) {
        users.setCreateTime(LocalDate.now());
        users.setUpdateTime(LocalDate.now());
        userMapper.insert(users);
    }

    @Override
    public Users selectuser(Integer id) {
        return userMapper.selectById(id);
    }

    /**
     * 修改密码
     * @param
     */
    public void updatapassword(UserUpdataPassword userUpdataPassword) {
        Users users = new Users();
        users.setId(BeanThread.get());
        Users users1 = userMapper.selectById(users.getId());
        if (userUpdataPassword.getOldpassword().equals(users1.getPassword())) {
            users1.setPassword(userUpdataPassword.getNewpassword());
            users1.setUpdateTime(LocalDate.now());
            userMapper.updateById(users1);
        }
        else {
            throw new BenEX("原密码错误");
        }
    }

    /**
     * 查询所有用户
     * @return
     */
    public List<Users> selectalluser() {
        List<Users> usersList = userMapper.selectList(null);
        return usersList;
    }
}
